import { createSlice } from "@reduxjs/toolkit";
import axios from 'axios'

const billStore = createSlice({
    name: 'billStore',
    initialState: {
        billList: []
    },
    reducers: {
        setBillList(state, action){
            state.billList = action.payload
        },
        // 新增一个对象
        insert(state, action){
            state.billList.push(action.payload)
        }
    }
})

const { setBillList, insert } = billStore.actions

const getBillList = () => {
    return async dispatch => {
        const res = await axios.get('http://localhost:8888/ka')
        dispatch(setBillList(res.data))
    }
}

// 异步请求，新增一个对象
const asyncInsert = data => {
    return async dispatch => {
        const res = await axios.post('http://localhost:8888/ka', data)
        dispatch(insert(data))
    }
}

const reducer = billStore.reducer
export { getBillList, asyncInsert }
export default reducer